package zhoug.common.screenrecord;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.projection.MediaProjectionManager;
import android.os.Build;

import zhoug.common.permission.ZPermissions;
import zhoug.logging.Logger;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

/**
 * 录屏
 * 使用前台服务录屏
 *
 * @Author: zhoug
 * @Date: 2024-09-03
 * @Description:
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class ScreenRecordManager {
    private static boolean DEBUG = true;
    private static final String TAG = ">>>ScreenRecordManager";

    private FragmentActivity mActivity;
    //录屏监听器
    private OnRecordVideoListener mOnRecordVideoListener;
    private MediaProjectionManager mMediaProjectionManager;
    private String mVideoKeepPath;//视频保存地址
    private ScreenRecordBroadcastReceiver mReceiver;
    //录屏服务前台通知
    private static IScreenRecordNotification screenRecordNotification;
    private final static SimpleScreenRecordNotification mDefNotification = new SimpleScreenRecordNotification();
    //录屏请求Launcher
    private ActivityResultLauncher<Intent> mScreenCaptureLauncher;

    public ScreenRecordManager(@NonNull FragmentActivity activity) {
        this.mActivity = activity;
        addObserver(activity.getLifecycle());
    }


    private void addObserver(Lifecycle lifecycle) {
        lifecycle.addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onCreate(@NonNull LifecycleOwner owner) {
                registerReceiver();
                mScreenCaptureLauncher = mActivity.registerForActivityResult(
                        new ActivityResultContracts.StartActivityForResult(),
                        result -> {
                            if (result != null) {
                                int resultCode = result.getResultCode();
                                Intent resultData = result.getData();
                                if (resultCode == Activity.RESULT_OK) {
                                    //启动录屏service服务，
                                    new ScreenRecordService.Launcher(mActivity)
                                            .setResultCode(resultCode)
                                            .setResultData(resultData)
                                            .setKeepPath(mVideoKeepPath)
                                            .start();
                                } else {
                                    if (null != mOnRecordVideoListener) {
                                        mOnRecordVideoListener.onError("请求录屏失败");
                                    }
                                }
                            }
                        }
                );
            }

            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                unregisterReceiver();
                if (mScreenCaptureLauncher != null) {
                    mScreenCaptureLauncher.unregister();
                }

                mOnRecordVideoListener = null;

            }
        });
    }


    /**
     * 权限申请+请求录屏
     */
    public void startRecord() {
        ZPermissions.with(mActivity)
                .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO)
                .setShowNoAsking(true)
                .setShowDescription(true)
                .setDescription("录屏需要获取储存,相机和录音权限")
                .setCallback((success, granted, denied) -> {
                    if (success) {
                        startRecord2();
                    }
                }).request();
    }

    /**
     * 请求录屏
     */
    public void startRecord2() {
        try {
            if (mMediaProjectionManager == null) {
                mMediaProjectionManager = (MediaProjectionManager) mActivity.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
            }
            if (mMediaProjectionManager == null) {
                if (null != mOnRecordVideoListener) {
                    mOnRecordVideoListener.onError("实例化录屏管理器失败");
                }
                return;
            }
            Intent screenCaptureIntent = mMediaProjectionManager.createScreenCaptureIntent();
            mScreenCaptureLauncher.launch(screenCaptureIntent);
        } catch (Exception e) {
            e.printStackTrace();
            if (null != mOnRecordVideoListener) {
                mOnRecordVideoListener.onError(e.getMessage());
            }
        }
    }

    /**
     * 停止录屏
     */
    public void stopRecord() {
        ScreenRecordService.stop(mActivity);
    }

    /**
     * 录像保存地址
     *
     * @param videoKeepPath
     */
    public void setVideoKeepPath(String videoKeepPath) {
        this.mVideoKeepPath = videoKeepPath;
    }

    /**
     * 设置录屏监听
     *
     * @param onRecordVideoListener
     */
    public void setOnRecordVideoListener(OnRecordVideoListener onRecordVideoListener) {
        this.mOnRecordVideoListener = onRecordVideoListener;
    }

    public static void setScreenRecordNotification(IScreenRecordNotification screenRecordNotification) {
        ScreenRecordManager.screenRecordNotification = screenRecordNotification;
    }

    static IScreenRecordNotification getScreenRecordNotification() {
        return screenRecordNotification == null ? mDefNotification : screenRecordNotification;
    }


    public static void setNotificationId(int id) {
        mDefNotification.setNotificationId(id);
    }

    public static void setNotificationChannel(String channelId, String channelName, String channelDescription) {
        mDefNotification.setNotificationChannel(channelId, channelName, channelDescription);

    }

    public static void setNotificationSmallIcon(@DrawableRes int smallIcon) {
        mDefNotification.setSmallIcon(smallIcon);
    }


    private static void sendBroadcastReceiver(Context context, int event, String msg) {
        if (DEBUG) {
            Logger.d(TAG, "sendBroadcastReceiver:event=" + event + ",msg=" + msg);
        }
//        Intent broadcast = new Intent(context, ScreenRecordBroadcastReceiver.class);
        Intent broadcast = new Intent();
        broadcast.setAction(ScreenRecordBroadcastReceiver.ACTION);
        broadcast.putExtra(ScreenRecordBroadcastReceiver.PARAM_EVENT, event);
        broadcast.putExtra(ScreenRecordBroadcastReceiver.PARAM_MSG, msg);
        context.sendBroadcast(broadcast);
    }

    static void sendStart(Context context) {
        sendBroadcastReceiver(context, ScreenRecordBroadcastReceiver.EVENT_START, null);
    }

    static void sendStop(Context context, String path) {
        sendBroadcastReceiver(context, ScreenRecordBroadcastReceiver.EVENT_STOP, path);
    }

    static void sendError(Context context, String error) {
        sendBroadcastReceiver(context, ScreenRecordBroadcastReceiver.EVENT_ERROR, error);
    }


    @SuppressLint("WrongConstant")
    private void registerReceiver() {
        if (DEBUG) {
            Logger.d(TAG, "registerReceiver:注册通知");
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ScreenRecordBroadcastReceiver.ACTION);
        mReceiver = new ScreenRecordBroadcastReceiver();
        ContextCompat.registerReceiver(mActivity, mReceiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED);
    }

    private void unregisterReceiver() {
        if (DEBUG) {
            Logger.d(TAG, "registerReceiver:取消注册通知");
        }
        if (mReceiver != null) {
            mActivity.unregisterReceiver(mReceiver);
        }
    }

    private class ScreenRecordBroadcastReceiver extends BroadcastReceiver {
        public static final String ACTION = "com.common.action.SCREEN_RECORD";
        public static final String PARAM_EVENT = "ScreenRecordEvent";
        public static final String PARAM_MSG = "ScreenRecordMsg";
        public static final int EVENT_START = 1;
        public static final int EVENT_STOP = 2;
        public static final int EVENT_ERROR = 3;


        public ScreenRecordBroadcastReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (DEBUG) {
                Logger.d(TAG, "onReceive");
            }
            if (intent != null && mOnRecordVideoListener != null) {
                String action = intent.getAction();
                if (ACTION.equalsIgnoreCase(action)) {
                    int event = intent.getIntExtra(PARAM_EVENT, 0);
                    String msg = intent.getStringExtra(PARAM_MSG);
                    if (event == EVENT_START) {
                        mOnRecordVideoListener.onStart();
                    } else if (event == EVENT_STOP) {
                        mOnRecordVideoListener.onStop(msg);
                    } else if (event == EVENT_ERROR) {
                        mOnRecordVideoListener.onError(msg);
                    }
                }

            }
        }
    }


}
